/*
 * Created on 29/04/2008
 */

package com.apbetioli.mapr.map;

import com.apbetioli.mapr.place.dao.PlacesDaoFactory;
import com.apbetioli.mapr.place.entity.GeoPoint;
import com.apbetioli.mapr.place.entity.Place;
import com.apbetioli.mapr.util.properties.PropertiesLoaderImpl;
import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author Alexandre Parra Betioli
 */
public class MapServletName extends HttpServlet {
   
    //Initial values
    
    double latitude  = Double.parseDouble( PropertiesLoaderImpl.getValue("config.properties", "gmaps.latitude") );
    double longitude = Double.parseDouble( PropertiesLoaderImpl.getValue("config.properties", "gmaps.longitude") );        
    double altitude  = Double.parseDouble( PropertiesLoaderImpl.getValue("config.properties", "gmaps.altitude") );

    String gmapsKey  = PropertiesLoaderImpl.getValue("config.properties", "gmaps.api.key");
    String pageTitle = PropertiesLoaderImpl.getValue("messages.properties", "page.title");
    String kmlDir    = PropertiesLoaderImpl.getValue("config.properties", "kml.url");

    int mapWidth  = Integer.parseInt( PropertiesLoaderImpl.getValue("config.properties", "gmaps.width") );
    int mapHeight = Integer.parseInt( PropertiesLoaderImpl.getValue("config.properties", "gmaps.height") );
    
    /** 
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
            //Validation
            
            String projectKeyParam = request.getParameter("key");
            String placeNameParam  = request.getParameter("place");
            
            String res = validate( projectKeyParam, placeNameParam );
            if( res != null ) {
                out.println(res);
                return;
            }
            
            // Building the page
            
            out.println("<html>");
            out.println("<head>");
            out.println("<meta http-equiv='content-type' content='text/html; charset=utf-8'/>");
            out.println("<title>" + pageTitle + "</title>");
            
            // Load Google's script
            
            
            out.println("<script src='http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=" + gmapsKey + "' type='text/javascript'/>");
            
            // Load own script 
            
            out.println("<script src='./javascript/mapScript.js' type='text/javascript'/>");
            out.println("</head>");

            // Load map in a given position
            
            String kmlUrl = kmlDir  + projectKeyParam + ".kml";
            
            out.println("<body onload=\"initialize('" + kmlUrl + "', " + latitude + ", " + longitude + ", " + altitude + " )\"  onunload=\"GUnload()\" >");
            out.println("<div id='map_canvas' style='width: " + mapWidth + "px; height: " + mapHeight + "px; float:left; border: 1px solid black;'></div>");
            out.println("</body>");
            out.println("</html>");
            
        } finally { 
            out.close();
        }
    } 

    private String validate(String projectKey, String placeName) {
        
            String example = "<br>Example: ...Map?key=123456789&place=Serra+da+Lagoa";
        
            if( projectKey == null )
                return "Please inform the key" + example;
            
            if( placeName == null )
                return "Please inform the place name" + example;
            
            placeName = placeName.replaceAll("+", " ");
            Place place = PlacesDaoFactory.getInstance(true).findByName(placeName);
            if( place != null ) {
                System.out.println( place );
                
                GeoPoint gp = place.getGeoPoint();
                if( gp != null ) {
                    latitude  = gp.getLatitude();
                    longitude = gp.getLongitude();
                }
            }
            
            return null;
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "The map";
    }

    // </editor-fold>
}
